/**
 * Copyright (C) 2016 Eshore Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eshore.thrpc.config.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.eshore.thrpc.RpcException;
import com.eshore.thrpc.common.ServerNode;
import com.eshore.thrpc.config.ServerConfig;
import com.eshore.thrpc.server.IServer;

/**
 * 服务提供者javabean
 * <p>
 * 
 * @author : zhouzhixiang
 * @date : 2016-11-18
 */
public class ServerBean extends ServerConfig implements InitializingBean {

    /** LOGGER */
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    /** javabean的ID */
    private String id;

    /**
     * getter method
     * 
     * @see ServerConfig#id
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * setter method
     * 
     * @see ServerConfig#id
     * @param id
     *            the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        export();
    }

    /**
     * 暴露服务
     * <p>
     * 
     * @throws ClassNotFoundException
     *             ,RpcException
     */
    public void export() throws ClassNotFoundException, RpcException {
        ServerNode serverNode = genServerNode();
        // 创建服务
        IServer server = createServer(serverNode);
        server.start();
        setServer(server);
        if (server.isStarted()) {
            try {
                // 服务注册
                // 添加关闭钩子
                addShutdownHook(server);
            } catch (Exception e) {
            	e.printStackTrace();
                LOGGER.error(e.getMessage(), e);
                server.stop();
            }
        } else {
            server.stop();
        }
    }

}
